Use
route
to indicate path, 80 is the default port for HTTP.1
2
3
4
5
6
7import bottle
def hello():
return "Hello World!"
bottle.run(host='localhost', port=80, debug=True)Dynamic path V.S. static path. We can use filter such as
<id:int>
to convert input variables to certain type.1
2
3
4
5
6
7import bottle
def hello(name,address):
return "Hello "+name
bottle.run(host='localhost', port=80, debug=True)Use local resources. Pay special attention to the path. Local resource names should start with ‘/‘.
1
2
3
def server_static(filename):
return bottle.static_file(filename, root='./resource/')The default HTTP request method for
route()
isget()
, we can use other methodspost()
,put()
,delete()
,patch()
. The POST method is commonly used for HTML form submission. When entering URL address, GET method is used.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28import bottle
def check_login(username, password):
if username=='niuli' and password=='niuli':
return True
else:
return False
def login():
return '''
<form action="/login" method="post">
Username: <input name="username" type="text" />
Password: <input name="password" type="password" />
<input value="Login" type="submit" />
</form>
'''
def do_login():
username = bottle.request.forms.get('username')
password = bottle.request.forms.get('password')
if check_login(username, password):
return "<p>Your login information was correct.</p>"
else:
return "<p>Login failed.</p>"
bottle.run(host='localhost', port=80, debug=True)Return local files
localhost/filename
. Notepath:path
is important, otherwise the filename containing ‘/‘ may not be correctly recognized.1
2
3
4
5from bottle import static_file
def server_static(filepath):
return static_file(filepath, root=’./resource’)Use
redirect
to jump to another page:bottle.redirect('/login')
Use the HTML template. In the template file, the lines starting with
%
are python codes and others are HTML codes. We can include other templates in the current template by using% include('header.tpl', title='Page Title')
. Cookies, HTTP header, HTML <form> fields and other request data is available through the globalrequest
object.1
2
3
4
5
6
7
8
9
10
def root(name="default"):
return bottle.template('my_template', name=name)
def do_login():
username = bottle.request.forms.get('username')
password = bottle.request.forms.get('password')
bottle.redirect('/'+username)Some tricks for helping development
bottle.debug(True)
The default error page shows a traceback. Templates are not cached. Plugins are applied immediately.run(reloader=True)
Every time you edit a module file, the reloader restarts the server process and loads the newest version of your code.